package geektime.io.bio;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.*;

/**
 * 利用传统id模拟客户端
 */
public class ClientDemo {

    public static void main(String[] args) {
        // 创建一个客户端，模拟接收服务端发送过来的信息
//        clientReceiveMessage();

        // 创建一个客户端，模拟向服务端发送信息
        clientSendMessage();
    }

//    public static void clientReceiveMessage() {
//        // 创建一个客户端，模拟接收服务端发送过来的信息
//        try (Socket clientSocket = new Socket(InetAddress.getLocalHost(), 9999);
//             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
//            bufferedReader.lines().forEach(System.out::println);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private static void clientSendMessage() {
        while (true) {
            // 循环创建一个客户端，模拟向服务端发送信息
            try(Socket clientSocket = new Socket(InetAddress.getLocalHost(), 9999);
                OutputStream outputStream = clientSocket.getOutputStream()) {
                // 阻塞，获取输入信息
                String message = new Scanner(System.in).nextLine();
                outputStream.write(message.getBytes());
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
